package cn.iocoder.yudao.module.iot.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * desc:工具类，用于手机号验证
 * @author:fuzhifei
 * @date:2023/12/18 18:30
 */

public class PhoneUtils {


    /**
     * 用于匹配手机号码
     */
    private final static String REGEX_MOBILEPHONE = "^0?1[34578]\\d{9}$";
    /**
     * 用于匹配固定电话号码
     */
    private final static String REGEX_FIXEDPHONE = "^(010|02\\d|0[3-9]\\d{2})?\\d{6,8}$";
    /**
     * 用于获取固定电话中的区号
     */
    private final static String REGEX_ZIPCODE = "^(010|02\\d|0[3-9]\\d{2})\\d{6,8}$";

    private static Pattern PATTERN_MOBILEPHONE;
    private static Pattern PATTERN_FIXEDPHONE;
    private static Pattern PATTERN_ZIPCODE;
    static {
        PATTERN_FIXEDPHONE = Pattern.compile(REGEX_FIXEDPHONE);
        PATTERN_MOBILEPHONE = Pattern.compile(REGEX_MOBILEPHONE);
        PATTERN_ZIPCODE = Pattern.compile(REGEX_ZIPCODE);
    }


    public static Map<String, String> checkNumber(String number) {
        Map<String, String> map = new HashMap<>();
        String phoneType = null;
        String code = null;

        if (number != null && number.length() > 0) {
            if (isCellPhone(number)) {
                // 如果手机号码以0开始，则去掉0
                if (number.charAt(0) == '0') {
                    number = number.substring(1);
                }
                phoneType = "手机";
                code = number.substring(0, 7);
            } else if (isFixedPhone(number)) {
                // 获取区号
                String zipCode = getZipFromHomephone(number);
                phoneType = "座机";
                code = zipCode;
            } else {
                phoneType = "无效手机";
                code = null;
            }
        }
        map.put("phoneType", phoneType);
        map.put("code", code);

        return map;
    }

    /**
     * 获取固定号码号码中的区号
     *
     * @param strNumber
     * @return
     */
    public static String getZipFromHomephone(String strNumber) {
        Matcher matcher = PATTERN_ZIPCODE.matcher(strNumber);
        if (matcher.find()) {
            return matcher.group(1);
        }

        return null;
    }

    /**
     * 判断是否为手机号码
     *
     * @param number 手机号码
     * @return
     */
    public static boolean isCellPhone(String number) {
        Matcher match = PATTERN_MOBILEPHONE.matcher(number);
        return match.matches();
    }

    /**
     * 判断是否为固定电话号码
     *
     * @param number 固定电话号码
     * @return
     */
    public static boolean isFixedPhone(String number) {
        Matcher match = PATTERN_FIXEDPHONE.matcher(number);
        return match.matches();
    }


    public static void main(String[] args) {
        System.out.println(checkNumber("051284619003"));
        System.out.println(checkNumber("13412249197"));
    }
}